Home Java Docker
Home     Java

Java Topic

What is Java
History of Java
Freature of Java
Difference Between Java & C++
Java Environment Set Up
Java Hello World Program & its Internal Process
Java Hello World Program
JDK, JRE and JVM
Java Variables
Java Data Types & Unicode System
Java Operators
Java Keywords
Java Control Statements
Java if else
Java switch
Java for loop
Java While loop
Java Do While loop
Java break
Java continue
Java Oops Concept
Java Object & Class
Java Method
Java Constructor
Java Static Keyword
Java this Keyword
Java Inheritance
Java Hybrid Inheritance
Aggregation(HAS-A)
Java Polymorphism
Java method overloading
Java method overriding
Java Runtime polymorphism
Java Dynamic Binding
Super keyword
Final keyword
Difference Between method overloading and method overriding
Java Abstraction
Java Interface
Abstract class vs Interface
Java Encapsulation
Java Package
Java Access Modifiers
covariant return type
Instance initializer block
Java instanceof operator
Object Cloning in Java
Wrapper classes in Java
Java Strictfp Keyword
Recursion in Java
Java Command Line Arguments
Difference between object and class
Java String
Java String Class
Java Immutable String
Java Immutable Class
String Buffer
String Builder
String Buffer vs String
String Builder vs String Buffer
String Tokenizer in Java
Java Array
Java Exceptions Handling
Java Try-Catch block
Java Multiply Catch Block
Java Finally Block
Java Throws Keyword
Java Throw Keyword
Java Exception Propagation
Java Throw vs Throws
Final vs Finally vs Finalize
Exception Handling With Method Overridding
Java Multithreading
Lifecycle and States of a Thread in Java
How to create a thread in Java
Thread Scheduler in Java
Sleeping a thread in Java
Calling run() method
Joining a thread in Java
Naming a thread in Java
Thread Priority
Daemon Thread
Thread Pool
Thread Group
Shutdown hook
Multitasking vs Multithreading
Garbage Collection
RunTime Class
Java Synchronization
Synchronized block in Java
Static Synchronization in Java
Deadlock in Java
Inter Thread Communication in Java
Interrupting Thread in Java
Reentrant Monitor in Java
Java Applet
Animation in Applet
EventHandling in Applet
Display image in Applet
Displaying Graphics in Applet
Parameter in Applet
Java 8 Features
Java Lambda Expressions
Method References
Functional Interfaces
Java 8 Stream
Base64 Encode Decode
Default Method
for Each() Method
Collectors class
String Joiner Class
Optional Class
JavaScript Nashron
Parallel Array Sort
Type Interface
Parameter Reflection
Type and Repeating Annotations
JDBC Improvements

Interface in Java

  • An interface is define as an abstract type in the Java that is used to define a class's behaviour. An interface is a template for behaviour in Java. Static constants and abstract methods are both parts of a Java interface.
  • An interface is a mechanism for achieving 100% abstraction in Java. Only abstract methods, not method bodies, are not allowed in the Java interface it means only method signature are devlared, no body. It is used in Java to provide abstraction and multiple inheritance. Java Interface represents the IS-A connection.


Table Of Content

  • Interface in Java
  • Uses of Interface
  • How to declare an interface
  • Java multiple inheritance with interface
  • JDK 8 : Static Method in Interface
  • JDK 8 : Default Method in Interface
  • Marker or Tagged Interface
  • Difference Between Class and Interface

We should describe an entity as an interface when we identify its type based on its behaviour rather than its properties.

An interface is same as class. it include variables and methods, but by default, the methods declared in an interface are abstract it means just method signature, no body.





Important point for Interface

  • The interface keyword should be used to declare an interface. It means complete abstraction. By default, all fields in an interface are public, static, and final, and all methods are declared with an empty body and are all public.
  • Any method that is declared in an interface must be implemented by the class that implements it and need to declare the implements keyword to implement/extends an interface.
  • The IS-A relationship is represented by the Java interface.
  • There is no constructor for an interface.
  • Java Interfaces cannot be created in the same way as we cerate abstract classes.
  • We can include default and static methods in an interface as of Java 8 and Private methods are now possible in interfaces from Java 9.
  • Interfaces define what a class needs to do it, not how to do it. It is the behavior's design manual.
  • If any class implements an interface but it does not provide method bodies for all of the interface's method then the class must be declared as abstract.

Uses an Interface

  • Total abstraction is achieved by using interface.
  • Java does not support multiple inheritances for classes, so multiple inheritances can be achived by using an interface.
  • Any class can implement an infinite number of interfaces but can only extend one other class.
  • To achieve loose coupling, interface is also used.
  • Abstraction improves the application's modularity.
  • The enhancement will be very simple in abstraction because we will be able to make changes to our internal system without affecting end users.




The compiler's internal addition to the interface

Before the interface method, the Java compiler adds the keywords public and abstract.


Before data members, the compiler also adds the public, static, and final keywords.

By default, interface fields are public, static, and final and interface methods are public and abstract .



Relationship between class and interface




How to declare an interface?




Syntax

 interface { 
   // declare constant fields      
   // declare methods that abstract       
   // by default.         
 }   


Java Interface Example


 // Java Interface Example  
interface Displayable {
	void display();
}
class Test implements Displayable {
	public void display(){
	System.out.println("Hello");
	}
}
class Main{
	public static void main(String[] args){
		Test test = new Test();
		test.display();
	}
}



Output:

Hello 


Java Interface Example

In below example Shape Interface has only one method draw but its implementation is provided by circle and triangle classes.It means interface is defined by someone else, but its implementation is provided by some other people and used by someone else but implementation part is hidden by the user who uses the interface.


interface Shape {
	void Draw();
}
class Triangle implements Shape {
	public void Draw(){
	 System.out.println("Drawing Triangle......");
	}
}
class Circle implements Shape {
	public void Draw(){
	 System.out.println("Drawing Circle......");
	}
}
class Main{
	public static void main(String[] args){
		Shape shape = new Triangle();
		shape.Draw();
		
		Shape shape2 = new Circle();
		shape2.Draw();
		
	}
}



Output:

Drawing Triangle 
Drawing Circle 


Java multiple inheritance with interface


Due to ambiguity, multiple inheritance is not supported in the case of classes. However, since there is no ambiguity in the case of an interface, it is supported.


Multiple inheritance occurs when a class implements multiple interfaces or when an interface extends multiple interfaces.


Multiple inheritance with interface
interface Shape {
	void Draw();
}
interface Displayable{  
  void Display();  
}  
class Circle implements Shape,Displayable { // multiple inheritance
	@Override
	public void Draw() {
		// TODO Auto-generated method stub
		System.out.println("Drawing Circle......");
	}
	
	@Override
	public void Display() {
		// TODO Auto-generated method stub
		System.out.println("Display Circle.");
	}
}
class Main{
	public static void main(String[] args){
		Circle circle = new Circle();
		circle.Draw();
		circle.Display();		
	}
}



Output:

Drawing Circle...... 
Display Circle. 


Interface Inheritance


Example of Interface inheritance
interface Displayable{  
    void Display();  
} 
interface Shape extends Displayable {
	void Draw();
}
class Circle implements Shape{ 
	@Override
	public void Draw() {
		// TODO Auto-generated method stub
		System.out.println("Drawing Circle......");
	}
	
	@Override
	public void Display() {
		// TODO Auto-generated method stub
		System.out.println("Display Circle");
	}
}
class Main{
	public static void main(String[] args){
		Circle circle = new Circle();
		circle.Draw();
		circle.Display();		
	}
}



Output:

Drawing Circle...... 
Display Circle 


JDK 8 : Static Method in Interface


Since java 8 static methods are defined in interfaces, they can be called without an object. however, these method are not inherited.


static method example
interface  Bike{
	void MaxSpeed();
    static void StaticCheck(){ //  Static method in interface 
        System.out.println("Static method  from interface ");
    }
}
class Hero implements Bike{   
   	 public void MaxSpeed() {
 		System.out.println("Max Speed is : 140 kmph");	
 	 }  
}
class Main{
	public static void main(String[] args) {
		Hero hero=new Hero();
		hero.MaxSpeed();
		Bike.StaticCheck(); // static method called without object creation
	}
}



Output:

Max Speed is : 140 kmph 
Static method  from interface  


JDK 8 : Default Method in Interface


Since Java 8, method body can be define in interfaces. However, we must make it default method with default keyword.


above concept is describe in below example
interface  Bike{
	void MaxSpeed();
	default void DefaultCheck(){ 
        System.out.println("Default method  from interface");
    }
}
class Hero implements Bike{   
   	 public void MaxSpeed() {
 		System.out.println("Max Speed is : 140 kmph");	
 	 }  
}
class Main{
	public static void main(String[] args) {
		Bike bike=new Hero();
		bike.MaxSpeed();
		bike.DefaultCheck();	
	}
}



Output:

Max Speed is : 140 kmph 
Default method  from interface 


Marker or Tagged Interface


An interface that contains neither methods nor constants is referred to as a marker interface. The compiler and JVM can learn more about the object because it provides run-time type information.


Marker interface is also called tagging interface.


Syntax

 public interface  Deletable { 
 }   





Comparison Chart

Difference Between Class and Interface are mention below


S.N Class Interface
1. we can instantiate variables and make objects in a class. we cannot instantiate variables and make an object in an interface.
2. Classes may include methods with implementation The implementation of methods is not permitted in the interface.
3. Classes can use the private, protected, and public access specifiers. Public is the only specifier used in Interface.





Abstract class vs Interface Next »
« Perv Next »


Post your comment





Read Next Topic
Java Tutorial - Topic
Java Abstraction
Java Interface
Abstract class vs Interface
Read Other Java Chapter
Java Topic
Java Basic Tutorial
Java Control Statements
Java Classes & Object
Java Inheritance
Java Polymorphism
Java Abstraction
Java Encapsulation
Java OOPs Miscellaneous
Java Array
Java String
Java Exception Handling
Java Multithreading
Java Synchronization
Java Applet
Java 8 Features
Java 9 Features
Java Collection
Java Mcq
Java Interview Question
Tools
  

Useful Links

  • Home
  • Blog
  • About us
  • Contact Us
  • Privacy policy

Contact Us

Police Colony
Patna, Bihar
India

Email:

About DockerTpoint


India's largest site for Programming Tutorial as well as BANK, SSC, RAILWAY exam
and Campus placement preparation.